/**
 * 
 */
package tk.redbluelotto.service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import tk.redbluelotto.util.CalculateUtil;

import com.ximpleware.AutoPilot;
import com.ximpleware.EOFException;
import com.ximpleware.EncodingException;
import com.ximpleware.EntityException;
import com.ximpleware.NavException;
import com.ximpleware.ParseException;
import com.ximpleware.VTDGen;
import com.ximpleware.VTDNav;
import com.ximpleware.XPathEvalException;
import com.ximpleware.XPathParseException;

/**
 * 5wan.com html分析噄1�7�1�7
 * 
 * @author zb
 * 
 */
public class WanHtmlParser {

	private static final String URL = "http://datachart.500.com/ssq/history/inc/history.php?limit=";

	private static String getLastNumURL(int num) {
		return URL + num;
	}
	
	public static long[] getlastValue(int num) throws UnsupportedEncodingException, IOException, EncodingException, EOFException, EntityException, ParseException, XPathParseException, XPathEvalException, NavException{
		return getlastValue(num,0);
	}
	
	public static long[] getlastValue(int num,int excludeNum) throws UnsupportedEncodingException, IOException, EncodingException, EOFException, EntityException, ParseException, XPathParseException, XPathEvalException, NavException{
		long[] lastValues = new long[num-excludeNum];
		String content = FetchLastNumber.loadFromWeb(getLastNumURL(num));
		content = content.substring(content.indexOf("tbody") - 1, content.lastIndexOf("tbody") + 6).replaceAll("&nbsp;", "");
		VTDGen vg = new VTDGen();
		vg.setDoc(content.getBytes("utf8"));
		vg.parse(true); 
		VTDNav vn = vg.getNav();
		AutoPilot ap = new AutoPilot(vn);
		ap.selectXPath("//td[@class='t_cfont2']");
		@SuppressWarnings("unused")
		int result = -1;
		int i = 0,count=0;
		StringBuilder reds = new StringBuilder(18);
		while ((result = ap.evalXPath()) != -1) {
			reds.append(vn.toNormalizedString(vn.getText())).append(" ");
			if(++i%6==0){
				lastValues[count++] = CalculateUtil.str2Long(reds.toString());
				reds = new StringBuilder(18); 
			}
		}
		return lastValues;
	}

	
}
